package com.netease.financial.base.pdf;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;

import com.netease.financial.R;
import com.netease.financial.common.security.SecurityJNI;
import com.netease.financial.common.util.DownloadManagerPro;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.common.util.preferences.DownloadPreferencesHelper;

import java.io.File;

/**
 * Created by wyf on 7/31/15.
 */
public class CloudPdfPresenterImpl implements CloudPdfPresenter {

    private static final String TAG = CloudPdfPresenterImpl.class.getSimpleName();

    private static final String DOWNLOAD_FOLDER_NAME = "download";

    private DownloadManager mDownloadManager;
    private DownloadManagerPro mDownloadManagerPro;

    private long mDownloadId = 0;

    private CompleteReceiver mCompleteReceiver;

    private CloudPdfView mCloudPdfView;
    private Context mContext;

    @Override
    public void requestPdf(String pdfUrl) {
        mCloudPdfView.showLoading();
        mDownloadId = DownloadPreferencesHelper.getDownloadIdForUrl(pdfUrl);

        NfsLog.d(TAG, "CloudPdfPresenter.pdfUrl = " + pdfUrl);
        downloadPdfIfNeed(pdfUrl);
    }

    private void downloadPdfIfNeed(String pdfUrl) {
        int status = mDownloadManagerPro.getDownloadStatus(mDownloadId);
        if (isDownloading(status)) {
            NfsLog.d(TAG, "isDownloading");
        } else {
            if (status == DownloadManager.STATUS_FAILED) {
                NfsLog.d(TAG, "STATUS_FAILED000");
                download(pdfUrl);
            } else if (status == DownloadManager.STATUS_SUCCESSFUL) {
                NfsLog.d(TAG, "STATUS_SUCCESSFUL111");
                renderPdf();
            } else {
                NfsLog.d(TAG, "else");
                download(pdfUrl);
            }
        }
    }

    @Override
    public void setView(CloudPdfView view) {
        mCloudPdfView = view;
        mContext = view.getContext();
    }

    @Override
    public void onCreate() {
        mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        mDownloadManagerPro = new DownloadManagerPro(mDownloadManager);

        mCompleteReceiver = new CompleteReceiver();
        /** register download success broadcast **/
        mContext.registerReceiver(mCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    @Override
    public void onDestroy() {
        mContext.unregisterReceiver(mCompleteReceiver);
    }

    public static boolean isDownloading(int downloadManagerStatus) {
        return downloadManagerStatus == DownloadManager.STATUS_RUNNING
                || downloadManagerStatus == DownloadManager.STATUS_PAUSED
                || downloadManagerStatus == DownloadManager.STATUS_PENDING;
    }

    private void download(String url) {
        String fileName = url.substring(url.lastIndexOf("/"));

        try {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, fileName);

            request.setTitle(mContext.getString(R.string.electronic_contract_text));
            request.setDescription(mContext.getString(R.string.downloading));
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
            request.setVisibleInDownloadsUi(false);
            request.addRequestHeader("AppId", SecurityJNI.getAppId());
            // request.allowScanningByMediaScanner();
            // request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
            // request.setShowRunningNotification(false);
            // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
            request.setMimeType("application/pdf");
            mDownloadId = mDownloadManager.enqueue(request);
            /** save download id to preferences **/
            DownloadPreferencesHelper.saveDownloadIdForUrl(url, mDownloadId);
        } catch (Exception e) {
            e.printStackTrace();
            mCloudPdfView.onError(mContext.getString(R.string.network_connection_timeout_error));
        }

    }

    class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            /**
             * get the id of download which have download success, if the id is my id and it's status is successful,
             * then install it
             **/
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (completeDownloadId == mDownloadId) {
                if (mDownloadManagerPro.getStatusById(mDownloadId) == DownloadManager.STATUS_SUCCESSFUL) {
                    renderPdf();
                } else {
                    mCloudPdfView.onError(mContext.getString(R.string.network_connection_timeout_error));
                }
            }
        }
    }

    private void renderPdf() {
        String filePath = mDownloadManagerPro.getFileName(mDownloadId);
        File file = new File(filePath);
        mCloudPdfView.renderPdf(Uri.fromFile(file));
        mCloudPdfView.hideLoading();
    }
}
